﻿using _4_NovaAdmin.Web.Core.IM;
using _4_NovaAdmin.Web.Core.ServiceExtensions;
using AspNetCoreRateLimit;
using StackExchange.Profiling;

namespace _4_NovaAdmin.Web.Core;

[AppStartup(int.MaxValue)]
public class Startup : AppStartup
{
    public IConfiguration config { get; set; }

    public override void ConfigureServices(IServiceCollection services)
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        services.AddResponseCaching();
        CorsSetup.AddCors(services);
        services.AddSwagger(config);
        services.AddMiniProfiler();
        services.AddDynamicApi();
        services.AddInjection();
        services.AddIpRateLimiting(config);
        services.AddAuthorize(config);
        services.AddHttpContextAccessor();
        services.AddConfigOptions(config);
        services.AddSingleton<ImUtility>();
        services.AddSingleton<ImClient>();
        services.AddSingleton<ImServer>();
    }

    public override void Configure(IApplicationBuilder app)
    {
        //var env = app.ApplicationServices.GetRequiredService<IWebHostEnvironment>();
        //app.UseIpRateLimiting();// 启用IP限流中间件
        app.UseException();//全局异常处理要放到最前面 ◎
        app.UseImServer();
        app.UseResponseCaching();
        app.UseCors("cors");
        app.UseStaticFiles();
        //app.UseIdempotency();//幂等中间件
        app.UseSwagger(config);
        // 配置路由
        app.UseRouting();
        // 使用 MiniProfiler
        app.UseMiniProfiler();
        // 开启认证
        app.UseAuthentication();
        // 开启授权中间件
        app.UseAuthorization();
        // 启用websocket中间件
        app.UseWebSockets();
        // 配置终结点
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
            endpoints.MapSwagger("{documentName}/api-docs");
        });
    }
}
